package com.atzxh.heima.netty.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import static com.atzxh.heima.netty.c1.ByteBufferUtil.debugAll;

/**
 * @author 小红同学
 * @date 2023-12-14-23:08
 * @description     单线程版
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 使用selector管理多个channel
        Selector selector = Selector.open();

        // 创建了服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 设置非阻塞
        ssc.configureBlocking(false);
        // 绑定监听端口
        ssc.bind(new InetSocketAddress(8080));

        // 注册channel
        SelectionKey sscKey = ssc.register(selector, 0, null);
        // key 只关注accept事件
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("register key : {}", sscKey);

        while (true) {
            // 使用select方法，没有事件发生，线程就会阻塞，有时事件恢复运行
            // select 在事件未处理是，它不会阻塞， 所以当事件发生时，要么处理，要么取消，不能置之不理。
            selector.select();
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                // 删除非常重要！！！！！！！
                keyIterator.remove();
                log.debug("key : {}", key);
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    SelectionKey scKey = socketChannel.register(selector, 0, buffer);
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("{}", socketChannel);
                    log.debug("scKey : {}", scKey);
                } else if (key.isReadable()) {
                    try {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        if (read == -1) {
                            // 此时客户端是正常断开， read 会返回 -1
                            key.cancel();
                        } else {
                            split(buffer);
                            if (buffer.position() == buffer.limit()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        // 这里一定要取消，不然客户端停止，会导致服务器崩掉。
                        key.cancel();
                    }
                }
//                key.cancel();
            }
        }
    }

    private static void split(ByteBuffer byteBuffer) {
        byteBuffer.flip();
        for (int i = 0; i < byteBuffer.limit(); i++) {
            // 找到一条完整信息
            if (byteBuffer.get(i) == '\n') {
                int length = i + 1 - byteBuffer.position();
                // 存到新的 ByteBuffer 中
                ByteBuffer target = ByteBuffer.allocate(length);
                // 从 byteBuffer 读，向 target 写
                for (int j = 0; j < length; j++) {
                    target.put(byteBuffer.get());
                }
                debugAll(target);
            }
        }
        byteBuffer.compact();
    }
}
